package com.sergio.compress.model.channelWapper;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.sergio.compress.model.base.ChannelWrapper;
import lombok.Data;
import org.springframework.util.StopWatch;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/15 20:02
 */
@Data
public abstract class HessianWrapper<T> extends ChannelWrapper<T> {

    @Override
    public String getChannelName() {
        return "Hessian";
    }

    @Override
    public byte[] serialize() {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            HessianOutput hessianOutput = new HessianOutput(outputStream);
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            hessianOutput.writeObject(this.dataSend);
            byte[] cborData = outputStream.toByteArray();
            stopWatch.stop();
            timeSe = stopWatch.getTotalTimeNanos();
            lengthSource = cborData.length;
            hessianOutput.close();
            outputStream.close();
            return cborData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

        }
    }

    @Override
    public void deserialize(byte[] source) {
        try {// 创建ProtobufMapper实例
            ByteArrayInputStream inputStream = new ByteArrayInputStream(source);
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            HessianInput hessianInput = new HessianInput(inputStream);

            T otherValue = (T) hessianInput.readObject();
            stopWatch.stop();
            timeDse = stopWatch.getTotalTimeNanos();
            this.resultSe = this.dataSend.equals(otherValue);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!this.resultSe) {
            throw new RuntimeException("反解析结果不一致!!!");
        }

    }

}
